package com.github.winyiwin.matrix.apollo.internals;

import com.ctrip.framework.apollo.spring.boot.ApolloApplicationContextInitializer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.util.StringUtils;

import java.util.Optional;

public class MatrixApolloContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext>,
        EnvironmentPostProcessor, Ordered {

    public static final int DEFAULT_ORDER = ApolloApplicationContextInitializer.DEFAULT_ORDER - 1;


    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {

        String appId = environment.getProperty("spring.application.name");
        String cacheDir = environment.getProperty("apollo.cacheDir", "/data/cacheDir");
        String namespaces = environment.getProperty("apollo.bootstrap.namespaces", "application,arch.pub_logs");
        if (!StringUtils.isEmpty(appId)) {
            System.setProperty("app.id", appId);
            System.setProperty("apollo.cacheDir", cacheDir);
            System.setProperty("apollo.bootstrap.enabled", "true");
            System.setProperty("apollo.bootstrap.eagerLoad.enabled", "true");
            System.setProperty("apollo.bootstrap.namespaces", namespaces);
        }
        //设置全局环境变量参数，如果不存在springboot的配置，则进行全局
        Optional.ofNullable(environment.getProperty("spring.profiles.active")).ifPresent(env -> System.setProperty("env", env));

    }


    @Override
    public int getOrder() {
        return DEFAULT_ORDER;
    }

    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
    }
}
